import { defineStore } from 'pinia'
import { ref } from 'vue'

export interface UserInfo {
  id: number
  username: string
  nickname: string
  email: string
  phone: string
  avatar: string
}

export const useUserStore = defineStore('user', () => {
  const userInfo = ref<UserInfo | null>(null)
  const token = ref<string>('')
  const isLogin = ref<boolean>(false)

  const setUserInfo = (info: UserInfo) => {
    userInfo.value = info
    isLogin.value = true
  }

  const setToken = (newToken: string) => {
    token.value = newToken
    localStorage.setItem('token', newToken)
  }

  const clearUserInfo = () => {
    userInfo.value = null
    token.value = ''
    isLogin.value = false
    localStorage.removeItem('token')
  }

  // 初始化时检查本地存储的token
  const init = () => {
    const localToken = localStorage.getItem('token')
    if (localToken) {
      token.value = localToken
      isLogin.value = true
      // 这里可以调用接口获取用户信息
    }
  }

  return {
    userInfo,
    token,
    isLogin,
    setUserInfo,
    setToken,
    clearUserInfo,
    init
  }
})